package com.yxs.school.util;

import java.io.*;


import com.yxs.school.api.entity.File;
import lombok.extern.log4j.Log4j2;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.FileInfo;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.web.multipart.MultipartFile;

/**
 * @version V1.0
 * @ClassName: FastDfsUtil
 * @Description: FastDfs文件管理简单工具类
 */
@Log4j2
public class FastDfsUtil {

    private static TrackerClient trackerClient = null;
    private static TrackerServer trackerServer = null;
    private static StorageServer storageServer = null;
    private static StorageClient storageClient = null;

    static {
        try {
            ClientGlobal.init("fdfs_client.conf");
            trackerClient = new TrackerClient();
            trackerServer = trackerClient.getConnection();
            storageClient = new StorageClient(trackerServer, storageServer);
        } catch (IOException | MyException e) {
            log.error("FastDfs工具类初始化失败!");
            throw new RuntimeException("FastDfs工具类初始化失败!");
        }
    }

    /**
     * @param @param  inputStream 文件流
     * @param @param  filename 文件名称
     * @param @return
     * @param @throws IOException
     * @param @throws MyException
     * @return String 返回文件在FastDfs的存储路径
     * @throws
     * @Title: fdfsUpload
     * @Description: 通过文件流上传文件
     */
    public static String fdfsUpload(MultipartFile file, InputStream inputStream, String filename) throws IOException, MyException {
        String suffix = ""; //后缀名
        try {
            suffix = filename.substring(filename.lastIndexOf(".") + 1);
        } catch (Exception e) {
            throw new RuntimeException("参数filename不正确!格式例如：a.png");
        }
        String savepath = ""; //FastDfs的存储路径
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buff)) != -1) {
            swapStream.write(buff, 0, len);
        }
        byte[] in2b = swapStream.toByteArray();
        String[] strings = storageClient.upload_file(file.getBytes(), suffix, null); //上传文件
        for (String str : strings) {
            savepath += "/" + str; //拼接路径
        }
        return savepath;
    }

    /**
     * @param @param  filepath 本地文件路径
     * @param @return
     * @param @throws IOException
     * @param @throws MyException
     * @return String 返回文件在FastDfs的存储路径
     * @throws
     * @Title: fdfsUpload
     * @Description: 本地文件上传
     */
    public static String fdfsUpload(String filepath) throws IOException, MyException {
        String suffix = ""; //后缀名
        try {
            suffix = filepath.substring(filepath.lastIndexOf(".") + 1);
        } catch (Exception e) {
            throw new RuntimeException("上传的不是文件!");
        }
        String savepath = ""; //FastDfs的存储路径
        //String[] strings = storageClient.upload_file(filepath.getBytes(), suffix, null);
        String[] strings = storageClient.upload_file(filepath, suffix, null); //上传文件
        for (String str : strings) {
            savepath += "/" + str; //拼接路径
        }
        return savepath;
    }

    /**
     * @param @param  savepath 文件存储路径
     * @param @param  localPath 下载目录
     * @param @return
     * @param @throws IOException
     * @param @throws MyException
     * @return boolean 返回是否下载成功
     * @throws
     * @Title: fdfsDownload
     * @Description: 下载文件到目录
     */
    public static boolean fdfsDownload(String savepath, String localPath) throws IOException, MyException {
        String group = ""; //存储组
        String path = ""; //存储路径
        try {
            int secondindex = savepath.indexOf("/", 2); //第二个"/"索引位置
            group = savepath.substring(1, secondindex); //类似：group1
            path = savepath.substring(secondindex + 1); //类似：M00/00/00/wKgBaFv9Ad-Abep_AAUtbU7xcws013.png
        } catch (Exception e) {
            throw new RuntimeException("传入文件存储路径不正确!格式例如：/group1/M00/00/00/wKgBaFv9Ad-Abep_AAUtbU7xcws013.png");
        }
        int result = storageClient.download_file(group, path, localPath);
        if (result != 0) {
            throw new RuntimeException("下载文件失败：文件路径不对或者文件已删除!");
        }
        return true;
    }

    /**
     * @param @param  savepath 文件存储路径
     * @param @return
     * @param @throws IOException
     * @param @throws MyException
     * @return byte[] 字符数组
     * @throws
     * @Title: fdfsDownload
     * @Description: 返回文件字符数组
     */
    public static byte[] fdfsDownload(String savepath) throws IOException, MyException {
        byte[] bs = null;
        String group = ""; //存储组
        String path = ""; //存储路径
        try {
            int secondindex = savepath.indexOf("/", 2); //第二个"/"索引位置
            group = savepath.substring(1, secondindex); //类似：group1
            path = savepath.substring(secondindex + 1); //类似：M00/00/00/wKgBaFv9Ad-Abep_AAUtbU7xcws013.png
        } catch (Exception e) {
            throw new RuntimeException("传入文件存储路径不正确!格式例如：/group1/M00/00/00/wKgBaFv9Ad-Abep_AAUtbU7xcws013.png");
        }
        bs = storageClient.download_file(group, path); //返回byte数组
        return bs;
    }

    /**
     * @param @param  savepath 文件存储路径
     * @param @return
     * @param @throws IOException
     * @param @throws MyException
     * @return boolean 返回true表示删除成功
     * @throws
     * @Title: fdfsDeleteFile
     * @Description: 删除文件
     */
    public static boolean fdfsDeleteFile(String savepath) throws IOException, MyException {
        String group = ""; //存储组
        String path = ""; //存储路径
        try {
            int secondindex = savepath.indexOf("/", 2); //第二个"/"索引位置
            group = savepath.substring(1, secondindex); //类似：group1
            path = savepath.substring(secondindex + 1); //类似：M00/00/00/wKgBaFv9Ad-Abep_AAUtbU7xcws013.png
        } catch (Exception e) {
            throw new RuntimeException("传入文件存储路径不正确!格式例如：/group1/M00/00/00/wKgBaFv9Ad-Abep_AAUtbU7xcws013.png");
        }
        int result = storageClient.delete_file(group, path); //删除文件，0表示删除成功
        if (result != 0) {
            throw new RuntimeException("删除文件失败：文件路径不对或者文件已删除!");
        }
        return true;
    }

    /**
     * @param @param  savepath 文件存储路径
     * @param @return
     * @param @throws IOException
     * @param @throws MyException
     * @return FileInfo 文件信息
     * @throws
     * @Title: fdfdFileInfo
     * @Description: 返回文件信息
     */
    public static FileInfo fdfdFileInfo(String savepath) throws IOException, MyException {
        String group = ""; //存储组
        String path = ""; //存储路径
        try {
            int secondindex = savepath.indexOf("/", 2); //第二个"/"索引位置
            group = savepath.substring(1, secondindex); //类似：group1
            path = savepath.substring(secondindex + 1); //类似：M00/00/00/wKgBaFv9Ad-Abep_AAUtbU7xcws013.png
        } catch (Exception e) {
            throw new RuntimeException("传入文件存储路径不正确!格式例如：/group1/M00/00/00/wKgBaFv9Ad-Abep_AAUtbU7xcws013.png");
        }
        FileInfo fileInfo = storageClient.get_file_info(group, path);
        return fileInfo;
    }


    /*    public static void main(String[] args) {
            FastDfsUtil fast = new FastDfsUtil();
            try {
                String str="shenningwuid";
                InputStream stream= new ByteArrayInputStream(str.getBytes());
                String txt = fast.fdfsUpload(stream, "txt");
                System.out.println(txt);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (MyException e) {
                e.printStackTrace();
            }
        }*/
//    public String[] uploadBreakpointFile(String group_name, String fileName, NameValuePair[] meta) {
//        String[] results = null;
//        File file = new File(fileName);
//        long originalFileSize = file.length();
//
//        byte[] file_buff;
//
//        //NameValuePair[] vars = new NameValuePair[]{new NameValuePair("fileName", fileName), new NameValuePair("fileSize", String.valueOf(originalFileSize))};
//        int number = (int) (originalFileSize / defaultSize), leftLength;
//        number = originalFileSize % defaultSize == 0 ? number : number + 1;
//        byte[] bytes;
//        try {
//            InputStream input = new FileInputStream(file);
//            file_buff = new byte[input.available()];
//            input.read(file_buff);
//
//            if (originalFileSize > defaultSize) {
//
//                // 如果文件块大，则实现分块上传，需要准备一个空的文件
//
//                for (int i = 0; i < number; i++) {
//                    if (originalFileSize - (i) * defaultSize < defaultSize) {
//                        leftLength = (int) (originalFileSize - (i) * defaultSize);
//                        leftLength = leftLength < 0 ? (int) originalFileSize : leftLength;
//                        bytes = new byte[leftLength];
//                        if (i == 0) {
//                            results = storageClient.upload_appender_file(group_name, bytes, 0, leftLength, FilenameUtils.getExtension(fileName), meta);
//                        } else {
//                            /*采用追加的方式*/
//                            storageClient.append_file(results[0], results[1], bytes, 0, leftLength);
//                        }
//                    } else {
//                        bytes = new byte[(int) defaultSize];
//                        leftLength = (int) defaultSize;
//                        if (i == 0) {
//                            results = storageClient.upload_appender_file(group_name, bytes, 0, leftLength, FilenameUtils.getExtension(fileName), meta);
//                        } else {
//                            /*采用追加的方式*/
//                            storageClient.append_file(results[0], results[1], bytes, 0, leftLength);
//                        }
//                    }
//                }
//                //写入内容
//                storageClient.modify_file(results[0], results[1], 0, file_buff, 0, file_buff.length);
//            } else {
//                //                 如果文件比默认的文件要小，则直接上传
//
//                results = storageClient.upload_file(group_name, file_buff, FilenameUtils.getExtension(fileName), meta);
//
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return results;
//
//    }
}
